import matplotlib.pyplot as plt
from matplotlib import rcParams
import numpy as np
from typing import Dict
import platform


def _configure_chinese_font():
    # 自动配置系统适用的中文字体
    system = platform.system()
    if system == "Windows":
        rcParams['font.sans-serif'] = ['SimHei', 'Microsoft YaHei']
    elif system == "Linux":
        rcParams['font.sans-serif'] = ['WenQuanYi Zen Hei', 'Noto Sans CJK SC']
    else:
        rcParams['font.sans-serif'] = ['Arial Unicode MS', 'PingFang SC']
    rcParams['axes.unicode_minus'] = False  # 解决负号显示问题


_configure_chinese_font()


class MatplotlibCharts:
    @staticmethod
    def create_score_distribution(grades: Dict[str, Dict[str, float]]) -> plt.Figure:
        # 生成成绩分布直方图
        plt.style.use('ggplot')
        fig, ax = plt.subplots(figsize=(6, 3.5), dpi=100)

        # 提取成绩数据
        scores = [v['score'] for v in grades.values()]
        if not scores:
            raise ValueError("没有可用的成绩数据")

        # 设置颜色分段
        colors = []
        for score in scores:
            if score >= 90:
                colors.append('#4CAF50')  # 优秀：绿色
            elif score >= 60:
                colors.append('#2196F3')  # 及格：蓝色
            else:
                colors.append('#FF5252')  # 不及格：红色

        # 绘制直方图
        n, bins, patches = ax.hist(
            scores,
            bins=10,
            edgecolor='black',
            alpha=0.7
        )

        # 应用颜色
        for patch, color in zip(patches, colors):
            patch.set_facecolor(color)


        # 设置标签
        ax.set_title("成绩分布直方图", pad=15, fontsize=12)
        ax.set_xlabel("分数段", fontsize=10)
        ax.set_ylabel("科目数量", fontsize=10)
        ax.grid(True, linestyle='--', alpha=0.6)

        plt.tight_layout()
        return fig

    @staticmethod
    def create_credit_pie(grades: Dict[str, Dict[str, float]]) -> plt.Figure:
        #成学分占比饼图
        plt.style.use('ggplot')
        fig, ax = plt.subplots(figsize=(6, 4), dpi=100)

        # 准备数据
        subjects = []
        credits = []
        other_credit = 0
        total_credit = sum(info['credit'] for info in grades.values())
        threshold = total_credit * 0.05  # 小于5%的合并

        for subj, info in grades.items():
            if info['credit'] >= threshold:
                subjects.append(subj)
                credits.append(info['credit'])
            else:
                other_credit += info['credit']

        if other_credit > 0:
            subjects.append("其他科目")
            credits.append(other_credit)

        # 绘制饼图
        wedges, texts, autotexts = ax.pie(
            credits,
            labels=subjects,
            autopct=lambda p: f'{p:.1f}%\n({p * total_credit / 100:.1f}学分)',
            startangle=90,
            colors=plt.cm.tab20.colors,
            wedgeprops={'linewidth': 1, 'edgecolor': 'white'},
            pctdistance=0.85,
            textprops={'fontsize': 8}
        )

        # 设置标题和中心空白
        ax.set_title(f"学分占比 (总计: {total_credit:.1f}学分)", pad=20, fontsize=12)
        centre_circle = plt.Circle((0, 0), 0.6, fc='white')
        ax.add_artist(centre_circle)

        # 调整标签样式
        plt.setp(autotexts, size=8, weight="bold", color='white')
        plt.setp(texts, size=9)

        plt.tight_layout()
        return fig